#include <SDL2/SDL.h>
#include <stdio.h>

#define ERR(msg) do { \
        fprintf(stderr, "%s at %d in %s\n", msg, __LINE__, __FILE__); \
        exit(1); \
    } while (0)

int main(int argc, char **argv)
{
    /* Init */
    if (SDL_Init(SDL_INIT_VIDEO) < 0) ERR(SDL_GetError());

    SDL_Window *win = SDL_CreateWindow("demo1", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
    if (!win) ERR(SDL_GetError());

    SDL_Surface *surface = SDL_GetWindowSurface(win);
    if (!surface) ERR(SDL_GetError());

    /* Load bitmap image */
    SDL_Surface *load_img = SDL_LoadBMP("img.bmp"); 
    if (!load_img) ERR(SDL_GetError());

    SDL_Surface *img1 = SDL_ConvertSurface(load_img, surface->format, 0);
    SDL_Surface *img2 = SDL_ConvertSurface(load_img, surface->format, 0);
    if (!img1 || !img2) ERR(SDL_GetError());
    SDL_FreeSurface(load_img);

    /* Processing event */
    int running = 1;
    SDL_Event event;
    while (running) {
        int render_img2 = 0;
        if (SDL_BlitSurface(img1, NULL, surface, NULL) < 0) 
            ERR(SDL_GetError());

        while (SDL_PollEvent(&event) != 0) {
            switch (event.type) {
            case SDL_QUIT:    running = 0;     break;
            case SDL_KEYDOWN: render_img2 = 1; break;
            case SDL_KEYUP:   render_img2 = 0; break;
            case SDL_MOUSEMOTION:              break;
            }

            if (render_img2) {
                SDL_Rect dest;
                dest.x = 160; dest.y = 120;
                dest.w = 320; dest.h = 240;
                if (SDL_BlitScaled(img2, NULL, surface, &dest) < 0) 
                    ERR(SDL_GetError());
            }
            /* Drawing */
            SDL_UpdateWindowSurface(win);
            SDL_Delay(100);

            if (!running) break;
        }
    }

    /* Free resource */
    SDL_FreeSurface(img1);
    SDL_FreeSurface(img2);
    SDL_DestroyWindow(win);
    SDL_Quit();

    exit(0);
}
